package com.jh.user.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.util.StringUtils;
import org.springframework.web.client.AsyncRestTemplate;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadPoolExecutor;


/**
 * @author Fuchun
 * @since 1.0
 */
@Configuration
@EnableScheduling
@EnableAsync
public class ScheduleConfig implements SchedulingConfigurer {

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(taskExecutor());
    }

    @Bean(destroyMethod = "shutdown")
    public ScheduledExecutorService taskExecutor() {
        return Executors.newScheduledThreadPool(10);
    }

    @Bean
    public ThreadPoolTaskExecutor asyncExecutor() {
        return taskExecutor("User-");
    }

    @Bean
    @LoadBalanced
    public AsyncRestTemplate asyncRestTemplate(ThreadPoolTaskExecutor asyncExecutor) {
        return new AsyncRestTemplate(asyncExecutor);
    }

    private static ThreadPoolTaskExecutor taskExecutor(String threadNamePrefix) {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 通常云服务器最大CPU核数为16，maxPoolSize 默认最大值为 Integer.MAX_VALUE
        int coreNumber = Runtime.getRuntime().availableProcessors();
        executor.setCorePoolSize(coreNumber);
        executor.setMaxPoolSize(coreNumber * 2);
        // 线程阻塞队列容量，默认值：Integer.MAX_VALUE
        executor.setQueueCapacity(256);
        if (StringUtils.hasText(threadNamePrefix)) {
            executor.setThreadNamePrefix(threadNamePrefix);
        } else {
            executor.setThreadNamePrefix("MyExecutor-");
        }
        // 线程饱和策略：调用者的线程会执行该任务,如果执行器已关闭,则丢弃.
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }
}
